package cn.znzz.cjm.product.controller;

import cn.znzz.cjm.basic.exception.BusinessException;
import cn.znzz.cjm.basic.util.AjaxResult;
import cn.znzz.cjm.basic.util.LoginContext;
import cn.znzz.cjm.basic.util.PageList;
import cn.znzz.cjm.org.domain.Employee;
import cn.znzz.cjm.org.mapper.EmployeeMapper;
import cn.znzz.cjm.pet.domain.Pet;
import cn.znzz.cjm.product.domain.Product;
import cn.znzz.cjm.product.query.ProductQuery;
import cn.znzz.cjm.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private IProductService productService;
    @Autowired
    private EmployeeMapper employeeMapper;

    @PostMapping
    public PageList<Product> queryPage(@RequestBody ProductQuery query, HttpServletRequest request){
        return productService.queryPage(query);
    }
    //服务上架
    @PostMapping("/onsale")
    public AjaxResult onSale(@RequestBody List<Long> ids){
        try {
            productService.onSale(ids);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
        }
    }

    //服务下架
    @PostMapping("/offsale")
    public AjaxResult offSale(@RequestBody List<Long> ids){
        try {
            productService.offSale(ids);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
        }
    }
    //根据id查询
    @GetMapping("/{id}")
    public Product queryById(@PathVariable("id") Long id){
        return productService.queryByIdDetail(id);
    }
    //处理寻主消息
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody Product product, HttpServletRequest request){
        try {
            Long loginId = LoginContext.getCurrentLogin(request).getId();
            Employee employee = employeeMapper.loadByLoginInfoId(loginId);
            product.setShop_id(employee.getShop_id());
            productService.add(product);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("系统繁忙");
        }
    }

}
